class Account < ActiveRecord::Base
  
  attr_accessor :password_confirmation
  attr_accessor :update_password

  validates :password, :confirmation => true, :if => :should_validate_password?
  validates :name, :presence   => true
  validates :email, :presence => true, :format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}

  has_and_belongs_to_many :categories
  has_and_belongs_to_many :documents
  
  def should_validate_password?
    update_password || new_record?
  end

  def password
    @password
  end

  def password=(password)
    @password = password
    return if password.blank?
    do_salt
    self.crypt_password = Account.encrypt password, self.salt
  end

  def self.authenticate(email, password)
    account = self.find_by_email email
    if account
      encrypt_password = self.encrypt password, account.salt
      if account.crypt_password != encrypt_password
        account = nil
      end
    end
    account
  end

  private

  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest(password + salt + Coordina::Application.config.secret_token)
  end

  def do_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
end
